package com.shwread.android.qysw.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.ciko.code.bean.UserBean;
import com.netease.nim.demo.NimCache;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.shwread.android.qysw.PushMessageService;
import com.shwread.http.util.Logger;

import logic.dao.UserDao;


public class BootReceiver
        extends
        BroadcastReceiver
{
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// if (intent.getAction().equals(
		// "com.shwread.android.qysw.push_message_destory")) {
		// TODO
		// 在这里写重新启动service的相关操作
		startUploadService(context);
		// }
		
	}
	
	private void startUploadService(Context context) {
		//登录云信平台
		doNimlogin(context, UserDao.getInstance(context).getLastLoginUser());
		Intent sevice = new Intent(context, PushMessageService.class);
		context.startService(sevice);
	}
	
	/**
	 * @Title: doNimlogin
	 * @Description: 云信登录接口
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	void doNimlogin(final Context context, final UserBean user) {
		if (user == null) return;
		NIMClient.getService(AuthService.class).login(new LoginInfo(user.getImAccount(), user.getImToken())).setCallback(new RequestCallback<LoginInfo>()
		{
			@Override
			public void onSuccess(LoginInfo param) {
				Logger.d("im login success");
				NimCache.setAccount(user.getImAccount());
				//登录成功更新到数据库
				UserDao.getInstance(context).updateNeteaseAccount(user.getAccount(), user.getImAccount(), user.getImToken());
			}
			
			@Override
			public void onFailed(int code) {
				if (code == 302 || code == 404)
				{
					//Toast.makeText(LoginActivity.this, "帐号或密码错误", Toast.LENGTH_SHORT).show();
					Logger.d("im login failed: " + "帐号或密码错误");
				}
			}
			
			@Override
			public void onException(Throwable exception) {
				Logger.d("im login failed: " + exception.getMessage());
			}
		});
	}
}
